#!/usr/bin/env node

/**
 * API Test Script
 * Simple script to test basic API functionality
 */

const axios = require('axios');
const fs = require('fs');
const path = require('path');

// API Configuration
const API_BASE_URL = 'http://localhost:3000/api';

// Test data
const testUser = {
  nickname: 'Test User',
  email: 'test@example.com',
  phone: '13800138000',
  bio: 'Test user for API testing'
};

const testActivity = {
  title: 'Test Activity',
  description: 'This is a test activity created by the API test script',
  type: 'sports',
  startTime: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // Tomorrow
  endTime: new Date(Date.now() + 24 * 60 * 60 * 1000 + 2 * 60 * 60 * 1000).toISOString(), // Tomorrow + 2 hours
  maxParticipants: 10,
  location: {
    name: 'Test Location',
    address: '123 Test Street',
    coordinates: {
      latitude: 39.9042,
      longitude: 116.4074
    }
  },
  tags: ['test', 'api', 'demo']
};

class ApiTester {
  constructor() {
    this.token = null;
    this.user = null;
    this.activity = null;
  }

  async test() {
    console.log('🧪 Starting API Tests...\n');
    
    try {
      // Test 1: Health Check
      await this.testHealthCheck();
      
      // Test 2: User Registration
      await this.testUserRegistration();
      
      // Test 3: User Login
      await this.testUserLogin();
      
      // Test 4: Get Current User
      await this.testGetCurrentUser();
      
      // Test 5: Create Activity
      await this.testCreateActivity();
      
      // Test 6: Get Activities
      await this.testGetActivities();
      
      // Test 7: Get Activity Detail
      await this.testGetActivityDetail();
      
      // Test 8: Update Activity
      await this.testUpdateActivity();
      
      // Test 9: Like Activity
      await this.testLikeActivity();
      
      // Test 10: Add Comment
      await this.testAddComment();
      
      console.log('\n✅ All tests passed!');
      
    } catch (error) {
      console.error('\n❌ Test failed:', error.message);
      process.exit(1);
    }
  }

  async makeRequest(method, url, data = null, headers = {}) {
    try {
      const config = {
        method,
        url: API_BASE_URL + url,
        headers: {
          'Content-Type': 'application/json',
          ...headers
        },
        timeout: 10000
      };

      if (this.token) {
        config.headers.Authorization = `Bearer ${this.token}`;
      }

      if (data) {
        config.data = data;
      }

      const response = await axios(config);
      
      if (response.data.success) {
        return response.data;
      } else {
        throw new Error(response.data.message || 'Request failed');
      }
    } catch (error) {
      if (error.response) {
        throw new Error(`HTTP ${error.response.status}: ${error.response.data.message || 'Request failed'}`);
      } else if (error.request) {
        throw new Error('Network error: No response received');
      } else {
        throw new Error(`Request setup error: ${error.message}`);
      }
    }
  }

  async testHealthCheck() {
    console.log('1. Testing Health Check...');
    const response = await this.makeRequest('GET', '/health');
    console.log('   ✅ Health check passed');
    return response;
  }

  async testUserRegistration() {
    console.log('2. Testing User Registration...');
    const response = await this.makeRequest('POST', '/auth/register', testUser);
    console.log('   ✅ User registration passed');
    return response;
  }

  async testUserLogin() {
    console.log('3. Testing User Login...');
    const loginData = {
      email: testUser.email,
      password: 'testpassword' // Note: In real implementation, you'd need password
    };
    
    // For testing, we'll simulate WeChat login
    const mockLoginData = {
      code: 'mock_wechat_code',
      userInfo: {
        nickName: testUser.nickname,
        avatarUrl: 'https://picsum.photos/200/200?random=999',
        gender: 1
      }
    };
    
    const response = await this.makeRequest('POST', '/auth/wechat-login', mockLoginData);
    this.token = response.data.token;
    this.user = response.data.user;
    console.log('   ✅ User login passed');
    console.log(`   📧 User: ${this.user.nickname} (${this.user._id})`);
    return response;
  }

  async testGetCurrentUser() {
    console.log('4. Testing Get Current User...');
    const response = await this.makeRequest('GET', '/auth/me');
    console.log('   ✅ Get current user passed');
    return response;
  }

  async testCreateActivity() {
    console.log('5. Testing Create Activity...');
    const activityData = {
      ...testActivity,
      creator: this.user._id
    };
    
    const response = await this.makeRequest('POST', '/activities', activityData);
    this.activity = response.data.activity;
    console.log('   ✅ Create activity passed');
    console.log(`   🎉 Activity: ${this.activity.title} (${this.activity._id})`);
    return response;
  }

  async testGetActivities() {
    console.log('6. Testing Get Activities...');
    const response = await this.makeRequest('GET', '/activities');
    console.log(`   ✅ Get activities passed (${response.data.activities.length} activities)`);
    return response;
  }

  async testGetActivityDetail() {
    console.log('7. Testing Get Activity Detail...');
    const response = await this.makeRequest('GET', `/activities/${this.activity._id}`);
    console.log('   ✅ Get activity detail passed');
    return response;
  }

  async testUpdateActivity() {
    console.log('8. Testing Update Activity...');
    const updateData = {
      title: 'Updated Test Activity',
      maxParticipants: 15
    };
    
    const response = await this.makeRequest('PUT', `/activities/${this.activity._id}`, updateData);
    console.log('   ✅ Update activity passed');
    return response;
  }

  async testLikeActivity() {
    console.log('9. Testing Like Activity...');
    const response = await this.makeRequest('POST', `/activities/${this.activity._id}/like`);
    console.log('   ✅ Like activity passed');
    return response;
  }

  async testAddComment() {
    console.log('10. Testing Add Comment...');
    const commentData = {
      content: 'This is a test comment from the API test script!'
    };
    
    const response = await this.makeRequest('POST', `/activities/${this.activity._id}/comments`, commentData);
    console.log('   ✅ Add comment passed');
    return response;
  }
}

// Run tests if script is executed directly
if (require.main === module) {
  console.log('🚀 Offline Gathering Backend - API Test\n');
  console.log('Make sure the backend server is running on http://localhost:3000\n');
  
  const tester = new ApiTester();
  tester.test().catch(console.error);
}

module.exports = ApiTester;